//
//  RegViewController.m
//  MyShoes
//
//  Created by mac on 11-6-26.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FindPwdViewController.h"
#import "iToast.h"
#import "GlobalVar.h"
@interface FindPwdViewController (PrivateMethods)
- (void)initTextField;
@end

@implementation FindPwdViewController
@synthesize dataTableView;
@synthesize usernameField;



-(void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"短信取回密码";
	[self initTextField];
	self.dataTableView = [[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]autorelease];
	dataTableView.delegate = self;
	dataTableView.dataSource = self;
	//[dataTableView setBackgroundColor:[UIColor whiteColor]];
	//dataTableView.scrollEnabled = NO;
	[self.view addSubview:self.dataTableView];
	UIBarButtonItem *rightButton =[[[UIBarButtonItem alloc]initWithTitle:@"确 定" 
																   style:UIBarButtonItemStyleDone 
																  target:self action:@selector(dosend:)]autorelease];	
	self.navigationItem.rightBarButtonItem = rightButton;

}

-(void)viewWillAppear:(BOOL)animated
{
	//[emailField becomeFirstResponder];
}


-(IBAction)dosend:(id)dosend
{
    if([usernameField.text length] == 0)
    {
        iToast *toast = [iToast makeText:@"请输入手机号!"];
        [toast show];
        return;
    }
    NSString *InputYZM = [(UITextField *)[self.view viewWithTag:9000] text];
    NSString *OldYZM = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"YZM"]];
    if(![InputYZM isEqualToString:OldYZM])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"验证码不正确，请重新输入！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确  定", nil];
        [alert show];
        [alert release];
        alert = nil;
        return;
    }
    
    
    [self textFieldShouldReturn:usernameField];
    
	HUD = [[[MBProgressHUD alloc] initWithView:self.view]autorelease];
    HUD.removeFromSuperViewOnHide = YES;
	[self.view addSubview:HUD];
	[HUD setLabelText:@"正在发送请求,请稍候..."];
	[HUD show:YES];
    
    
    net_work=[[NewNetWork alloc]init];
    [net_work setDelegate:self];
    
    
    
    
    NSString* prepareMD5=[NSString stringWithFormat:@"%@%@%@",usernameField.text,SOFT_ID,@"ysw"];
    
    NSString* md5Str=[net_work Getmd5code:prepareMD5];
    
    
    
    
    NSString* CanShu=[NSString stringWithFormat:@"mobile=%@&softid=%@&ysw&md5=%@&multiAgent=%@&apiurl=%@&apn=%@",usernameField.text,SOFT_ID,md5Str,MULTIAGENTSWITCH,origin_url_prefix,NETWORKSTATE];
    NSLog(@"找回密码参数:%@",CanShu);
    
    
    
   
    
    
    
    
    [net_work getNetUrl:[NSString stringWithFormat:@"%@/%@",[GlobalVar getPrefixUrl],@"getpass.php"] CanShu:CanShu];
    
    


    [[NSUserDefaults standardUserDefaults] setObject:usernameField.text forKey:@"TempPhoto"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
	

}

-(void)Delegate_FeedBack:(NetRequest *)sender value:(NSString *)str{
    [HUD hide:YES];

    int xx1 = [str rangeOfString:@"<code>"].location;
    NSString *Str11 = [str substringFromIndex:xx1];
    xx1 = [Str11 rangeOfString:@"</code>"].location;
    Str11 = [Str11 substringToIndex:xx1];
    Str11 = [Str11 stringByReplacingOccurrencesOfString:@"<code>" withString:@""];
    
    if([Str11 isEqualToString:@"0"]){
        iToast *toast = [iToast makeText:@"提交成功，请等待系统发送短信!"];
        [toast show];
        [self performSelector:@selector(returntoFrontView:) withObject:nil afterDelay:1.0f];
    }else{
        iToast *toast = [iToast makeText:@"提交失败!"];
        [toast show];
    }
    
    if(Net_Request != nil){
        [Net_Request release];
        Net_Request = nil;
    }
}

-(void)Delegate_FeedBackFail:(NetRequest *)sender value:(NSString *)errorStr
{
    iToast* toast=[iToast makeText:errorStr];
    [toast show];
}

-(void)getTheAnalysizeResults:(NSString *)result
{
    [HUD hide:YES];
    
    NSString* code=[[result componentsSeparatedByString:@"|"] objectAtIndex:0];
    
    if ([code isEqualToString:@"1"]) {
        iToast *toast = [iToast makeText:@"提交成功，请等待系统发送短信!"];
        [toast show];
        [self performSelector:@selector(returntoFrontView:) withObject:nil afterDelay:1.0f];
    }else
    {
        iToast *toast = [iToast makeText:@"提交失败!"];
        [toast show];
    }
    
    
    if (net_work!=nil) {
        [net_work release];
        net_work=nil;
    }
    
    
}


-(void)getFailResults:(NSString *)errorResult
{
    
}


-(void)poptoParent
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)returntoFrontView:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView 
{ 
	return 1; 
}


- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{
	return 3;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = indexPath.row;
    if (row ==0 || row == 1)
    {
        return 45;
    }else {
        return 55;
    }
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *editableCellIdentifier = @"editableCellIdentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
							 editableCellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
									   reuseIdentifier:editableCellIdentifier] autorelease];
	}
	
	UIView *textField = [cell viewWithTag:100];
	if (textField) {
		[textField removeFromSuperview];
	}
		
	int row = [indexPath row];
	if (row == 0) {
		cell.textLabel.text = @"手机号：";
		[cell.contentView addSubview:usernameField];
	}else if (row == 1)
    {
    
        cell.textLabel.text = @"验证码：";
        UITextField *txt = [[UITextField alloc] initWithFrame:CGRectMake(80, 5, 100, 35)];
        [txt setTag:9000];
        [txt setDelegate:self];
        [txt setTextAlignment:NSTextAlignmentCenter];
        [txt setBorderStyle:UITextBorderStyleRoundedRect];
        [txt setFont:[UIFont systemFontOfSize:16]];
        [txt setBackgroundColor:[UIColor clearColor]];
        [cell.contentView addSubview:txt];
        [txt release];
        UIButton *Btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [Btn setFrame:CGRectMake(200, 5, 90, 35)];
        [Btn addTarget:self action:@selector(ShowTiShi) forControlEvents:UIControlEventTouchUpInside];
        [Btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cell.contentView addSubview:Btn];
        
    }else if (row == 2)
    {
		
        UILabel *phoneLabel = [[[UILabel alloc]initWithFrame:CGRectMake(5, 5, 285, 40)]autorelease];
        phoneLabel.font = [UIFont systemFontOfSize:14];
        phoneLabel.textColor = [UIColor grayColor];
        phoneLabel.tag = 100;
        phoneLabel.numberOfLines =0;
        phoneLabel.text = @"请输入您注册的手机号码，验证通过后，系统将会把您的帐号和密码发短信到您的手机。";
        phoneLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:phoneLabel];
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        [self showMessageView:@""];
    }
}
-(void)ShowTiShi
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:
                          
                          [NSString stringWithFormat:@"需要发送一条普通短信验证手机号码，短信费由运营商收取，%@不收取任何费用，现在获取验证码?",SOFT_NAME]
                          
                          delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
    alert = nil;
}

- (void)showMessageView:(NSString *)tel
{
    
    if( [MFMessageComposeViewController canSendText] ){
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init]; //autorelease];
        
        controller.recipients = [NSArray arrayWithObject:tel];
        
        NSString * YanZheng = [NSString stringWithFormat:@"%d%d%d%d",arc4random() % 10 + 1,arc4random() % 10 + 1,arc4random() % 10 + 1,arc4random() % 10 + 1];
        
        //保存验证码
        [[NSUserDefaults standardUserDefaults] setObject:YanZheng forKey:@"YZM"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        controller.body = YanZheng;
        controller.messageComposeDelegate = self;
        
        [self presentModalViewController:controller animated:YES];
        
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"推荐好友"];//修改短信界面标题
        
        
    }else{
        
        [self alertWithTitle:@"提示信息" msg:@"设备没有短信功能"];
    }
}

- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg {
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];
    
}


//MFMessageComposeViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    [controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES
    
    switch ( result ) {
            
        case MessageComposeResultCancelled:
            SMSSuccess = FALSE;
//            [self alertWithTitle:@"提示信息" msg:@"发送取消"];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"提示信息" msg:@"发送失败"];
            SMSSuccess = FALSE;
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送成功"];
            SMSSuccess = YES;
            break;
        default:
            break;
    }
}



/**
 * 初始化TextField
 */
- (void)initTextField {
	for (int i = 0; i < 5; i++) {
		UITextField *textField = [[[UITextField alloc] init] autorelease];
		textField.frame = CGRectMake(95, 10, 200.0, 25.0);
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		textField.returnKeyType = UIReturnKeyDone;
		textField.delegate = self;
		textField.tag = 100;
		if (i == 0){
			self.usernameField = textField;
			textField.placeholder = @"请输入手机号";
            textField.keyboardType = UIKeyboardTypeEmailAddress;
		}
	}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    self.dataTableView.frame  = self.view.bounds;
    [UIView commitAnimations];

	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{

    if(textField.tag == 9000){
        if(textField.tag == 9000){
            if([textField.text length] == 4){
                [self.navigationItem.rightBarButtonItem setEnabled:YES];
            }
        }
    }else{
    
        if(self.dataTableView.frame.size.height !=200){
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3f];
            [UIView setAnimationCurve:UIViewAnimationCurveLinear];
            self.dataTableView.frame  = CGRectMake(0, 0, 320, 200);
            [UIView commitAnimations];
        }
    }
}


- (void)dealloc {
   

	[usernameField release];
	[dataTableView release];
    [super dealloc];
}


@end
